from django.db import transaction
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from cards.models import Card, CustomerCard
from finance.api.utils import update_account


class CardSerializer(ModelSerializer):
    """
    优惠卡
    """
    status_name = serializers.CharField(source="get_status_display", read_only=True)

    class Meta:
        model = Card
        exclude = ["update_time", "add_time"]


class CustomerCardSerializer(ModelSerializer):
    """
    客户优惠卡
    """
    card_code = serializers.CharField(source="card.code", read_only=True)
    card_money = serializers.CharField(source="card.money", read_only=True)
    customer_name = serializers.CharField(source="customer.name", read_only=True)
    account_name = serializers.CharField(source="account.name", read_only=True)
    sale_class_name = serializers.CharField(source="get_sale_class_display", read_only=True)
    status_name = serializers.CharField(source="get_status_display", read_only=True)

    class Meta:
        model = CustomerCard
        exclude = ["update_time", "add_time"]

    def create(self, validated_data):
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            instance = None
            try:
                sale_class = validated_data.get('sale_class', 0)
                instance = self.Meta.model.objects.create(**validated_data)
                if sale_class == 1:   # 销售
                    # 收款账号增加
                    update_account(instance.account_id, -1 * instance.actual_money)

            except Exception as e:
                print(e)
                transaction.savepoint_rollback(save_id)

            transaction.savepoint_commit(save_id)
        return instance

    def update(self, instance, validated_data):
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                instance.card = validated_data.get('card', instance.card)
                instance.customer = validated_data.get('customer', instance.customer)

                old_account_id = instance.account_id
                instance.account = validated_data.get('account', instance.account)

                old_sale_class = instance.sale_class

                instance.sale_class = validated_data.get('sale_class', instance.sale_class)

                old_actual_money = instance.actual_money

                instance.actual_money = validated_data.get('actual_money', instance.actual_money)
                instance.receipt_order_code = validated_data.get('receipt_order_code', instance.receipt_order_code)
                instance.receipt_time = validated_data.get('receipt_time', instance.receipt_time)
                instance.status = validated_data.get('status', instance.status)
                instance.remark = validated_data.get('remark', instance.remark)
                instance.user = validated_data.get('user', instance.user)

                instance.save()

                if old_sale_class == 1 and instance.sale_class == 1:      # 销售
                    # 收款账号修改
                    update_account(old_account_id, old_actual_money)
                    update_account(instance.account_id, -1 * instance.actual_money)
                else:
                    if old_sale_class != 1 and instance.sale_class == 1:
                        update_account(instance.account_id, -1 * instance.actual_money)
                    elif old_sale_class == 1 and instance.sale_class != 1:
                        update_account(old_account_id, old_actual_money)

            except Exception as e:
                print(e)
                transaction.savepoint_rollback(save_id)

            transaction.savepoint_commit(save_id)

        return instance

